#include <ezfb.h>
#include <basic.h>

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

			SURFACE		sfScreen, sfBuffer;
STATIC		INT			fd;

BOOL		EZFBAPI		InitEzfbLibrary(
						) {
	struct fb_var_screeninfo varInfo;

	fd	= open("/dev/fb0", O_RDWR);
	if (fd < 0)
		goto __ERROR_EXIT;

	if (ioctl(fd, FBIOGET_VSCREENINFO, &varInfo) < 0)
		goto __ERROR_DEV_OPENED;

	if (varInfo.bits_per_pixel != BITS_PER_PIXEL)
		goto __ERROR_DEV_OPENED;

	sfScreen.cx = varInfo.xres;
	sfScreen.cy = varInfo.yres;
	sfScreen.lnBitPerPixel	= varInfo.bits_per_pixel;
	sfScreen.lnBytePerLine	= varInfo.xres * varInfo.bits_per_pixel / 8;
	sfScreen.lnTotalBytes	= varInfo.xres * varInfo.yres * varInfo.bits_per_pixel / 8;
	sfScreen.lpBits	= mmap(
		NULL,
		varInfo.xres * varInfo.yres * varInfo.bits_per_pixel / 8,
		PROT_READ | PROT_WRITE,
		MAP_SHARED,
		fd,
		0
		);

	if (NULL == sfScreen.lpBits)
		goto __ERROR_DEV_OPENED;

	sfBuffer		= sfScreen;
	sfBuffer.lpBits	= malloc(sfBuffer.lnTotalBytes);

	if (NULL == sfBuffer.lpBits)
		goto __ERROR_MEM_MAPPED;

	return TRUE;

__ERROR_MEM_MAPPED:
	munmap(sfScreen.lpBits, sfScreen.lnTotalBytes);
__ERROR_DEV_OPENED:
	close(fd);
__ERROR_EXIT:
	return FALSE;
}

VOID		EZFBAPI		FreeEzfbLibrary(
						) {
	free(sfBuffer.lpBits);
	munmap(sfScreen.lpBits, sfScreen.lnTotalBytes);
	close(fd);
}

VOID		EZFBAPI		Refresh(
						BOOL bDirection
						) {
	LPSURFACE lpSrc, lpDes;
	if (bDirection) {
		lpSrc = &sfBuffer;
		lpDes = &sfScreen;
	} else {
		lpSrc = &sfScreen;
		lpDes = &sfBuffer;
	}
	memcpy(lpDes->lpBits, lpSrc->lpBits, lpSrc->lnTotalBytes);
}
